package org.xg.study.servlet;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author CMG
 * @version 1.0
 * @description
 * @cLassName MySessionListener
 * @date 2021/9/24 16:30
 **/
@WebListener
public class MyBindingListener implements HttpSessionListener, HttpSessionAttributeListener {
    private String username;
    public MyBindingListener(String username) {
        super();
        this.username = username;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public MyBindingListener() {
    }
    @SuppressWarnings("unchecked")
    public void valueBound(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        ServletContext application = session.getServletContext();
        // 把用户名放入在线列表
        List<String> onlineUserList = (List) application.getAttribute("onlineUserList");
        // 第一次使用前，需要初始化
        if (onlineUserList == null) {
            onlineUserList = new ArrayList<String>();
        }
        onlineUserList.add(this.username);
        application.setAttribute("onlineUserList", onlineUserList);
        System.out.println("*******用户：" + this.username + "  已经成功加入在线用户列表");
    }
    @SuppressWarnings("unchecked")
    public void valueUnbound(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        ServletContext application = session.getServletContext();
        // 从在线列表中删除用户名
        List<String> onlineUserList = (List<String>) application.getAttribute("onlineUserList");
        onlineUserList.remove(this.getUsername());
        application.setAttribute("onlineUserList", onlineUserList);
        System.out.println(this.username + "退出。");
        System.out.println("当前在线人数:" + onlineUserList.size());
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {

    }
}
